package com.universe.datastructure.sparsearray;

/**
 * @Description: 稀疏数组（以五子棋举例）
 * @Author: chenhuan
 * @Date: 19:20 2019/12/6
 */
public class SparseArray {
    public static void main(String[] args) {
        //创建棋盘 11*11 0:无棋子 1：黑 2：白
        int arr[][] = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        arr[3][3] = 1;
        System.out.println("原始的二维数组···");
        for (int[] row : arr) {
            for (int data : row) {
                System.out.print(data + " ");
            }
            System.out.println();
        }
        //统计非0的数目（有效数字）
        int sum = 0;
        for (int[] row : arr) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        //创建对应的稀疏数组
        int[][] spareArr = new int[sum + 1][3];
        spareArr[0][0] = 11;
        spareArr[0][1] = 11;
        spareArr[0][2] = sum;

        //遍历非0数填充到稀疏数组
        int count = 0; //统计稀疏数组的行数；
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    spareArr[count][0] = i;
                    spareArr[count][1] = j;
                    spareArr[count][2] = arr[i][j];
                }
            }
        }
        //遍历稀疏数组
        System.out.println("打印转化后的稀疏数组···");
        for (int i = 0; i < sum + 1; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(spareArr[i][j] + " ");
            }
            System.out.println();
        }

        //转换成文件

        //文件转稀疏数组

        //稀疏数组转原始数组
        int originArr[][] = new int[spareArr[0][0]][spareArr[0][1]];
        for (int i = 1; i < spareArr.length; i++) {
            originArr[spareArr[i][0]][spareArr[i][1]] = spareArr[i][2];
        }

        System.out.println("打印还原后的稀疏数组···");
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                System.out.print(originArr[i][j] + " ");
            }
            System.out.println();
        }

    }
}
